package com.fly.video.downloader.content.analyzer;

import com.fly.video.downloader.ResourceTable;
import com.fly.video.downloader.bean.Video;
import com.fly.video.downloader.content.analyzer.app.DouyinV3;
import com.fly.video.downloader.contract.VideoParser;
import com.fly.video.downloader.core.exception.URLInvalidException;
import com.fly.video.downloader.core.os.AsyncTaskResult;
import com.fly.video.downloader.exception.VideoException;
import com.fly.video.downloader.util.Helpers;
import ohos.app.Context;

public class AnalyzerTask implements Runnable  {

    private Context context;
    private AnalyzeListener listener;
    private String str;

    public AnalyzerTask(Context context, AnalyzeListener listener,String str)
    {
        this.context = context;
        this.listener = listener;
        this.str=str;
    }

    @Override
    public void run() {
        VideoParser parser = null;

        if (Helpers.containsDouyin(context, str)) {
            parser = DouyinV3.getInstance(this.context);
        }

        try {
            if (parser == null)
                throw new URLInvalidException(this.context.getString(ResourceTable.String_exception_invalid_url));

            Video video = parser.get(str);

            if (video == null || video.isEmpty())
                throw new VideoException(this.context.getString(ResourceTable.String_exception_invalid_video));

            listener.onAnalyzed(new AsyncTaskResult<>(video).getResult());

        } catch (Throwable e) {
            listener.onAnalyzeError(new AsyncTaskResult<>(e).getError());
        }
    }

    public interface AnalyzeListener {
        void onAnalyzed(Video video);
        void onAnalyzeCanceled();
        void onAnalyzeError(Throwable e);
    }
}
